package cc.uncarbon.module.appapi.service;


import cc.uncarbon.module.appapi.mapper.AppointmentMapper;
import cc.uncarbon.module.appapi.model.request.AppointMentDTO;
import cc.uncarbon.module.appapi.model.response.AppointmentItemBO;
import cc.uncarbon.module.appapi.model.vo.AppointmentVO;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yanrumiao.entity.AppointmentEntity;
import com.yanrumiao.enumns.AppointmentStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class AppointmentService {
    @Autowired
    private AppointmentMapper appointmentMapper;
    private static final int LOOKAHEAD_DAYS = 7;
    private static final String DATE_FORMAT = "MM-dd";
    private static final String TIME_FORMAT = "HH:mm";

    public List<AppointmentVO> getDataList(Long staffId) {

        // 指定时区，例如使用 UTC
        LocalDate today = LocalDate.now(ZoneId.of("Asia/Shanghai"));
        List<AppointmentVO> dates = new ArrayList<>();
        for (int i = 0; i < LOOKAHEAD_DAYS; i++) {
            LocalDate date = today.plusDays(i);
            String label = getLabel(date);
            List<AppointmentItemBO> timeList = getTimeList(date, label,staffId);
            dates.add(createAppointmentVO(date, label, timeList));
        }

        return dates;
    }

    public static AppointmentVO createAppointmentVO(LocalDate date, String label, List<AppointmentItemBO> timeList) {
        AppointmentVO vo = new AppointmentVO();
        DateTimeFormatter formatterDate = DateTimeFormatter.ofPattern(DATE_FORMAT); // 创建格式化器
        vo.setDate(date.format(formatterDate));
        vo.setLabel(label);
        vo.setItems(timeList);
        vo.setDateValue(date);
        return vo;
    }

    //获取时间名称，今天、明天、星期
    public static String getLabel(LocalDate date) {
        LocalDate today = LocalDate.now(); // 当前日期
        if (date.equals(today)) {
            return "今天";
        } else if (date.equals(today.plusDays(1))) {
            return "明天";
        } else {
            DayOfWeek week = date.getDayOfWeek();
            switch (week) {
                case MONDAY:
                    return "周一";
                case TUESDAY:
                    return "周二";
                case WEDNESDAY:
                    return "周三";
                case THURSDAY:
                    return "周四";
                case FRIDAY:
                    return "周五";
                case SATURDAY:
                    return "周六";
                case SUNDAY:
                    return "周日";
                default:
                    return "";
            }
        }
    }

    //获取当前日期下的时间
    public  List<AppointmentItemBO> getTimeList(LocalDate date, String label,Long staffId) {
        LocalTime startTime = LocalTime.of(9, 0); // 开始时间：早九点
        LocalTime endTime = LocalTime.of(21, 0); // 结束时间：晚九点
        Duration interval = Duration.ofMinutes(30); // 时间间隔：半小时
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(TIME_FORMAT);
        // 使用 Stream 生成时间点序列
        Stream<LocalTime> timeStream = Stream.iterate(startTime, time -> time.plus(interval))
                .limit(endTime.toSecondOfDay() / interval.getSeconds() + 1)
                .filter(time -> time.isBefore(endTime) || time.equals(endTime));

        // 收集时间点到列表并打印
        List<LocalTime> timePoints = timeStream.collect(Collectors.toList());
        List<AppointmentItemBO> boList = new ArrayList<>(timePoints.size());

        timePoints.forEach(item -> {
            AppointmentItemBO bo = new AppointmentItemBO();

            if (label.equals("今天")) {
                if (item.isAfter(LocalTime.now())) {
                    if(getAppointmentList(staffId, date, item)){
                        bo.setStatus(AppointmentStatusEnum.BANNED);
                    }else{
                        bo.setStatus(AppointmentStatusEnum.ENABLED);
                    }

                } else {
                    bo.setStatus(AppointmentStatusEnum.BANNED);
                }
            } else {
                if(getAppointmentList(staffId, date, item)){
                    bo.setStatus(AppointmentStatusEnum.BANNED);
                }else{
                    bo.setStatus(AppointmentStatusEnum.ENABLED);
                }
            }

            bo.setTime(item.format(formatter));
            bo.setTimeValue(item);
            boList.add(bo);
        });
        return boList;
    }
     //查询预约表
    private Boolean getAppointmentList(Long staffId, LocalDate date, LocalTime time) {
        List<AppointmentEntity> entityList = appointmentMapper.selectList(new QueryWrapper<AppointmentEntity>().lambda()
                .eq(AppointmentEntity::getStaffId, staffId)
                .eq(AppointmentEntity::getDate, date)
                .eq(AppointmentEntity::getTime, time));
        if(!entityList.isEmpty()){
            return true;
        }else{
            return false;
        }
    }

    public Long insert(AppointMentDTO dto) {
        AppointmentEntity entity = new AppointmentEntity();
        BeanUtil.copyProperties(dto,entity);
        appointmentMapper.insert(entity);
        return entity.getId();
    }
}


